package algorithm;

import org.junit.jupiter.api.Test;

public class SingleLinkedList {


    Node head;

    public void insertTail(int val) {
        if (head == null){
            insertToHead(val);
            return;
        }


        Node q = head;

        while (q.next != null) {
            q = q.next;
        }

        Node newNode = new Node(val);
        q.next = newNode;
    }

    public void insertToHead(int val) {
        Node newNode = new Node(val);
        newNode.next = head;
        head = newNode;
    }

    public boolean delete(int val){
        if (head==null)
            return false;
        Node p=head;
        Node q=null;
        while (p!=null&&p.data!=val){
            q=p;
            p=p.next;
        }

        if (p==null){
            return false;
        }

        if (q==null){
            head=head.next;
        }else {
            q.next=p.next;
        }

        return true;
    }

    public void printAll(){
        if (head==null)
            return;
        Node q=head;
        while (q!=null){
            System.out.print(q.data+" ");
            q=q.next;
        }

        System.out.println("");
    }

    @Test
    public void test(){
        SingleLinkedList link=new SingleLinkedList();
        int[] data={1,2,5,3,1};
        for (int i=0;i<data.length;i++){
            link.insertTail(data[i]);
        }
        link.insertToHead(99);
        link.printAll();
        link.delete(0);
        link.printAll();
    }

    public static class Node {
        int data;
        Node next;

        public Node(int data) {
            this.data = data;
        }
    }
}
